<?php
/**
 * (logic) （临时转正式）Payment第三方发货FBA费
 */
namespace App\Logic\MonthlyReportLT\ParseTmp;

use App\Models\MonthlyReportLT\Payment\PaymentThFee;
use App\Models\MonthlyReportLT\Tmp\TmpThFee;
use App\Models\Product\ProductAmazonSku;

class ParsePaymentThFee
{
    public static function exeParse($date){
        //临时
        $lines = TmpThFee::query()->selectRaw('sku,sum(total) as total')
            ->where('report_date',$date)
            ->groupBy('sku')
            ->get();
        $i = 0;
        $num = 100;
        $data = [];
        while(true){
            if($lines->isEmpty())break;
            $_lines = $lines->splice($i,$num);
            foreach ($_lines as $line){
                $pSkuId = ProductAmazonSku::getValueByCode($line->sku,'psku_id');
                if(!array_key_exists($pSkuId,$data)){
                    $data[$pSkuId] = $line->total;
                }else{
                    $data[$pSkuId] += $line->total;
                }
            }
        }
        foreach ($data as $pSkuId =>$total){
            if(!$pSkuId)$pSkuId = 0;
            PaymentThFee::query()
                ->updateOrCreate(['report_date' => $date,
                    'psku_id' => $pSkuId],
                    ['total' => abs($total)]);
        }
    }
}
